package cn.commander.base;

import cn.commander.baseEntity.DataEntity;
import cn.commander.model.response.ResponseData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.List;

/**
 * @Description: 基础服务
 * @Created by:
 * @Date: 2016/7/27 15:35
 * @Version: 1.0
 */
public abstract class BaseService<T extends DataEntity<T>, PK extends Serializable> {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	protected ResponseData getResponseData() {
		return new ResponseData();
	}

	private BaseMapper<T, PK> baseMapper;

	/**
	 * 插入或更新数据
	 *
	 * @param bean
	 * @return
	 */
	public int insertOrUpdate(T bean) {
		if (bean == null) {
			return 0;
		}
		if (bean.getIsNewRecord()) {
			bean.preInsert();
			return baseMapper.insertSelective(bean);
		} else {
			bean.preUpdate();
			return baseMapper.updateByPrimaryKeySelective(bean);
		}
	}

	/**
	 * 查询
	 *
	 * @param id
	 * @return
	 */
	public T findByPrimaryKey(PK id) {
		return baseMapper.selectByPrimaryKey(id);
	}

	/**
	 * 查询
	 *
	 * @param ids
	 * @return
	 */
	public List<T> findByPrimaryKeys(List<PK> ids) {
		return baseMapper.selectByPrimaryKeys(ids);
	}


	/**
	 * 查询
	 *
	 * @param bean
	 * @return
	 */
	public List<T> findList(T bean) {
		return baseMapper.selectBySelective(bean);
	}

	/**
	 * 删除数据
	 *
	 * @param id
	 * @return
	 */
	public int deleteByPrimaryKey(PK id) {
		return baseMapper.deleteByPrimaryKey(id);
	}

	public BaseMapper<T, PK> getBaseMapper() {
		return baseMapper;
	}

	public void setBaseMapper(BaseMapper<T, PK> baseMapper) {
		this.baseMapper = baseMapper;
	}


}
